package dht.message;
import dht.*;
import java.nio.ByteBuffer;


public abstract class AcceptMessage extends PaxosMessage {

    // these massages have
    // [ OpCode (2 bytes) | proposalNum (4 bytes) | value (n bytes) ]
    // the host that this message is asking to vote 
    // on for being leader
    private final Star value;

    public Star getValue() {
        return value;
    }
    private byte[] bytes;

    @Override
    public byte[] getBytes() {
        synchronized (this) {
            if (bytes == null) {
                // opcode proposal_num, star.id, star.period, star.magnitude
                int size = 2 + 4 + 4 + 8 + 8;
                bytes = ByteBuffer.allocate(size)
                        .putShort(getOpCode().value())
                        .putInt(getProposalNumber())
                        .putInt(value.id)
                        .putDouble(value.magnitude)
                        .putDouble(value.period)
                        .array();
            }
            return bytes;
        }
    }

    public AcceptMessage(OpCode opCode, int proposalNum, HostAddress addr, Star value) {
        super(opCode, proposalNum, addr);
        this.value = value;
    }

    public AcceptMessage(byte[] data, HostAddress addr) {
        super(data, addr);
        double mag, period;
        int id;
        ByteBuffer buff = ByteBuffer.wrap(data);
        id = buff.getInt(6);
        mag = buff.getDouble(10);
        period = buff.getDouble(18);
        this.value = new Star(id, period, mag);
    }

    @Override
    public String toString() {
        return getOpCode() + " with proposal# : " + getProposalNumber() + " value " + value;
    }
}
